<?php


namespace App\Services\Admin;

use App\Models\Admin;
use App\Models\AdminToken;
use App\Models\Role;
use Illuminate\Support\Facades\Crypt;

class AdminService
{
    public function __construct(){

    }

    /**
     * 注册
     * @param $data
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function register($data){
        $admin = new Admin();
        $safe_key = GenerateSafeKey(16);
        $admin->username = trim($data['username']);
        $admin->avatar = '/upload/images/header.jpg';
        $admin->safe_key = $safe_key;
        $admin->role_id = 2;  //注册成功，默认角色普通管理员
        $admin->password = Crypt::encrypt($safe_key.trim($data['password']));

        if ($admin->save()){
            return Success('注册成功！');
        }else{
            return Error();
        }
    }

    /**
     * 登录
     * @param $data
     */
    public function login($data){
        $user = Admin::where('username',trim($data['username']))->first();
        if (!$user){
            return Error('用户名不正确！');
        }
        if (!$user->status){
            return Error('账户已禁用，请联系管理员！');
        }

        //验证角色可用
        if ($user->role_id){
            $role = Role::find($user->role_id);
            if (!$role->status){
                return Error('角色《'.$role->role_name.'》已禁用，请联系管理员！', 401);
            }
        }

        $password = Crypt::decrypt($user->password);
        if ($password !== $user->safe_key.trim($data['password'])){
            return Error('密码不正确！');
        }

        //存储令牌、过期时间
        $exist = AdminToken::where('user_id',$user->id)->first();
        if ($exist && $exist->expire_time > time()){
            $result = [
                'userId' => $user->id,
                'nickName' => $user->nickname,
                'token' => $exist->token
            ];
            $adminToken = $exist;
        }else{
            $token = $this->generate_user_token($user->id);
            $result = [
                'userId' => $user->id,
                'nickName' => $user->nickname,
                'token' => $token
            ];

            $adminToken = new AdminToken();
            $adminToken->user_id = $user->id;
            $adminToken->token = $token;
        }

        if (isset($data['remember'])){
            $remember = 3600*24*30;
        }else{
            $remember = 3600*24*7;
        }

        $adminToken->expire_time = date('Y-m-d H:i:s',time() + $remember);
        if ($adminToken->save()){
            return Success('登录成功！',(object)$result);
        }else{
            return Error('登录失败！',(object)$result);
        }
    }

    public function getUserInfo($id){
        $user = Admin::find($id);
        unset($user->safe_key);
        unset($user->password);
        return $user;
    }

    /**
     * 获取后台用户列表
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAccountList($params){
        $take = $params['pageSize']?:10;
        $skip = (($params['page']?:1) - 1) * $take;
        $where = array();

        //检索条件
        $admins = Admin::where($where)
            ->skip($skip)
            ->take($take)
            ->get(['id', 'username', 'nickname', 'avatar', 'email', 'created_at', 'description', 'role_id', 'status']);
        foreach ($admins as $admin){
            $admin->role_name = $admin->role->role_name;
        }
        return Success('ok', $admins);
    }

    /**
     * 检测用户名是否存在
     * @param $username
     * @return \Illuminate\Http\JsonResponse
     */
    public function accountExist($username){
        $exist = Admin::where('username',trim($username))->first();
        if ($exist){
            return Error('该名称已存在！');
        }
        return Success();
    }

    /**
     * 设置管理员状态
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function setAdminStatus($params){
        $admin = Admin::find($params['id']);
        $admin->status = $params['status'];
        if ($admin->save()){
            return Success('sss',$admin);
        }else{
            return Error();
        }
    }

    /**
     * 新建/更新 账户
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function createOrUpdateAccount($data){
        if ($data['isUpdate']){
            $admin = Admin::find($data['id']);

            //更新密码
            if ($data['password']){
                $admin->password = Crypt::encrypt($admin->safe_key.trim($data['password']));
            }

            //检查用户名
            if (trim($data['username']) !== $admin->username){
                $exist_user = Admin::where('username', trim($data['username']))
                    ->first();
                if ($exist_user){
                    return Error('该用户名已存在！');
                }
            }
        }else{
            $exist_user = Admin::where('username', trim($data['username']))
                ->first();
            if ($exist_user){
                return Error('该用户名已存在！');
            }

            if (!isset($data['password'])){
                return Error('请输入密码！');
            }
            $safe_key = GenerateSafeKey(16);
            $admin = new Admin();
            $admin->safe_key = $safe_key;
            $admin->avatar = 'https://analyse.wszzl.cn/resource/img/avatar.jpg';
            $admin->password = Crypt::encrypt($safe_key.$data['password']);
        }

        $admin->username = trim($data['username']);
        $admin->email = trim($data['email']);
        $admin->role_id = $data['role_id'];
        $admin->nickname = trim($data['nickname']);
        $admin->description = trim($data['description']);


        if ($admin->save()){
            return Success('操作成功！');
        }else{
            return Error('操作失败！');
        }

    }

    /**
     * 登出
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout(){
        return Success();
    }

    /**
     * 生成token
     * @param $userId
     * @return string
     */
    protected function generate_user_token($userId){
        $token = Crypt::encrypt($userId.time());
        return $token;
    }
}
